<!-- 管理 -->
<template>
  <div class="app-container">
    <!-- 列表 -->
    <el-col>
      <div v-if="isShowSearchBtn" class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="关键字" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="菜单名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never" class="table-container">
        <template #header>
          <div class="flex justify-between">
            <div>
              <el-button
                v-hasPerm="['wechatmenu@del']"
                type="success"
                @click="openDialog()"
              >
                <template #icon><i-ep-plus /></template>
                新增</el-button
              >
              <el-button
                v-hasPerm="['wechatmenu@del']"
                type="danger"
                v-if="removeIds.length > 0"
                @click="handleDelete()"
                ><i-ep-delete />删除</el-button
              >
            </div>
            <div>
              <el-button
                class="ml-3"
                title="展开/折叠"
                @click="expandTable"
                icon="Sort"
                circle
              />
              <el-button
                class="ml-3"
                title="同步"
                @click="syncMenu"
                icon="Upload"
                circle
              />
              <el-button
                class="ml-3"
                title="搜索"
                @click="handleSearchShowBtn"
                icon="Search"
                circle
              />
              <el-button
                class="ml-3"
                title="刷新"
                @click="handleQuery"
                icon="Refresh"
                circle
              />
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="pageData"
          row-key="id"
          fit
          :default-expand-all="tableExpandAll"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="菜单名称" width="140px" align="left">
            <template #default="scope">
              <span class="link-type" @click="openDialog(scope.row.id)">{{
                scope.row.title
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" prop="type">
            <template #default="scope">
              <span v-if="scope.row.type === 'view'">
                <el-tag effect="dark" type="success">网页</el-tag>
              </span>
              <span v-if="scope.row.type === 'click'">
                <el-tag effect="dark" type="primary">点击</el-tag>
              </span>
              <span v-if="scope.row.type === 'miniprogram'">
                <el-tag effect="dark" type="warning">小程序</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="网页/链接" align="center" prop="url" />

          <el-table-column label="小程序AppId" align="center" prop="appid" />

          <el-table-column label="小程序路径" align="center" prop="url" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="创建时间" align="center" prop="created_at" />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button
                v-hasPerm="['wechatmenu@edit']"
                type="primary"
                @click="openDialog(scope.row.id)"
                circle
                icon="edit"
                title="编辑"
              />
              <el-button
                v-hasPerm="['wechatmenu@del']"
                type="danger"
                @click="handleDelete(scope.row.id)"
                circle
                title="删除"
                icon="delete"
              />
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.p"
          v-model:limit="queryParams.limit"
          @pagination="handleQuery"
        />
      </el-card>
    </el-col>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="上级" prop="parent_id">
          <el-select
            v-model="formData.parent_id"
            clearable
            placeholder="请选择父级菜单"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="formData.type" @change="menuType">
            <el-radio-button label="网页" value="view" />
            <el-radio-button label="点击" value="click" />
            <el-radio-button label="小程序" value="miniprogram" />
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="isShowTypeClick" label="点击类型" prop="key">
          <el-select
            v-model="formData.key"
            clearable
            placeholder="请选择点击类型"
          >
            <el-option
              key="rselfmenu_0_0"
              label="扫码带提示"
              value="rselfmenu_0_0"
            />
            <el-option
              key="rselfmenu_0_1"
              label="扫码推事件"
              value="rselfmenu_0_1"
            />
            <el-option
              key="rselfmenu_1_0"
              label="系统拍照发图"
              value="rselfmenu_1_0"
            />
            <el-option
              key="rselfmenu_1_1"
              label="拍照或者相册发图"
              value="rselfmenu_1_1"
            />
            <el-option
              key="rselfmenu_1_2"
              label="微信相册发图"
              value="rselfmenu_1_2"
            />
            <el-option
              key="rselfmenu_2_0"
              label="发送位置"
              value="rselfmenu_2_0"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="网页/链接" prop="url">
          <el-input v-model="formData.url" placeholder="请输入网页/链接" />
        </el-form-item>
        <el-form-item v-if="isShowType" label="小程序AppId" prop="appid">
          <el-input v-model="formData.appid" placeholder="请输入小程序AppId" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="0" />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElLoading } from "element-plus";

defineOptions({
  name: "WechatMenu",
  inheritAttrs: false,
});

import {
  fetchList,
  getMenuForm,
  addMenu,
  updateMenu,
  getSelectData,
  syncData,
  deleteMenu,
} from "@/api/wechatMenu";

import { MenuInfo, MenuQuery, MenuForm } from "@/api/wechatMenu/types";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const loading = ref(false); //  加载状态
const isShowType = ref(false);
const isShowTypeClick = ref(false);
const tableExpandAll = ref(true);
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<MenuQuery>({
  p: 1,
  limit: 10,
});

const total = ref(0); // 数据总数
const pageData = ref<MenuInfo[]>(); // 用户分页数据
const options = ref<OptionType[]>();

const isShowSearchBtn = ref(false);

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<MenuForm>({});

// 校验规则
const rules = reactive({
  title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  fetchList(queryParams)
    .then(({ data }) => {
      const list: any = data;
      pageData.value = list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 同步数据 */
function syncMenu() {
  ElMessageBox.confirm("是否将自定义菜单数据同步到微信公众号", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: "数据同步中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      syncData()
        .then(() => {
          loading.close();
          ElMessage.success("同步成功");
        })
        .finally(() => loading.close());
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消同步",
      });
    });
}

/**
 * 打开弹窗
 *
 * @param id ID
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改";
    getMenuForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
      if (formData.parent_id === 0) {
        formData.parent_id = undefined;
      }
    });
    getSelectData().then(({ data }) => {
      options.value = data;
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 关闭弹窗

 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        updateMenu(userId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addMenu(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  const data = {
    ids: ids,
  };
  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteMenu(data).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}
//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

function menuType(params: any) {
  isShowType.value = params === "miniprogram";
  isShowTypeClick.value = params === "click";
}

async function expandTable() {
  tableExpandAll.value = tableExpandAll.value === false;
  await nextTick();
}

onMounted(() => {
  handleQuery();
});
</script>
